<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace builder\uploads;

use Yii;
use yii\helpers\FileHelper;

/**
 * 本地驱动
 * @author cleverstone
 * @since ym2.0
 */
class LocalProvider extends BaseProvider
{
    /**
     * @var string 保存目录
     */
    public $webroot = '@webroot/uploads/';
    /**
     * @var string 文件链接
     */
    public $web = '@web/uploads/';

    /**
     * @var string 盐值
     */
    public $salt = '大 鹏 一 日 同 风 起 扶 摇 直 上 九 万 里';

    /**
     * Init
     * @throws \yii\base\Exception
     * @throws \yii\base\InvalidConfigException
     */
    protected function initOptions()
    {
        parent::initOptions();

        $this->webroot = Yii::getAlias($this->webroot) . $this->scenario . '/';
        $this->web = Yii::getAlias($this->web) . $this->scenario . '/';
        if (!is_dir($this->webroot)) {
            FileHelper::createDirectory($this->webroot);
        }
    }

    /**
     * 运行
     * @param bool $deleteTempFile
     * @return bool
     */
    protected function run($deleteTempFile = true)
    {
        list($filename, $savePath) = $this->_getUniqueFilename();

        $this->link = $this->web . $filename;

        if (!$this->uploadFile->saveAs($savePath, $deleteTempFile)) {
            $this->error = 'File upload failure!';
            return false;
        }

        return true;
    }

    /**
     * 获取唯一文件名
     * @param int $i 索引值
     * @return array
     */
    private function _getUniqueFilename($i = 0)
    {
        $name = md5($this->hash . $this->salt) . ($i ? "_$i" : '');
        $filename = $name . '.' . $this->ext;
        $savePath = $this->webroot . $filename;

        if (is_file($savePath)) {
            return $this->_getUniqueFilename(++$i);
        }

        return [$filename, $savePath];
    }
}